# -*- coding: utf-8 -*-
import logging, gzip, json, time, traceback
from datetime import datetime, date
from flask import Response, make_response
from flask_restful import Resource, reqparse, abort, current_app, request
from adminApp.extensions import db, redis_store
from ..utils.JsonToDatetime import JsonToDatetime
from adminApp.models import Machine, TaskLog, NetWorkCard


logger = logging.getLogger(__name__)
result = dict(status=200)


def build_result(status, message, data=None):
    return dict(status=status, message=message, data=data)
    # return gzip.compress(json.dumps(dict(status=status, message=message, data=data)).encode('utf-8'), 9)


class ReceivePushData(Resource):
    '''
    接收monclient 的post推送
    '''

    def post(self):
        try:
            data = json.loads(json.loads(gzip.decompress(request.data).decode('utf-8')))
            # 检测必须参数 系统UUID
            if not data.get('system_uuid'):
                return {'status':200, "msg":"uuid cant empty"}
            system_uuid = data.get('system_uuid').strip()
            if data.get('post_type')=='heart_beat' and data.get('data') and data.get('data').get('default_nic_rx_tx'):
                # 设备发送的上下行 带宽记录,记录到redis,用于web端ajax查看
                redis_store.set(current_app.config.get('RD_DEF_NETIO').format(system_uuid), json.dumps(data.get('data').get('default_nic_rx_tx')), ex=10)
                # 上下行记录到redis,后台任务保存到数据库，用于生成实时带宽使用率图片,及95带宽计费 点提取
                redis_store.rpush(current_app.config.get('RD_FLOW_DATA_LIST'), json.dumps((system_uuid, data.get('data').get('default_nic_rx_tx'))))
                # 查看设备ID 键值是否存在
                if not redis_store.exists(current_app.config.get('RD_MACHINE_EXISTS').format(system_uuid)):
                    # 若不存在，则添加到任务列表，会根据设备ID生成一条记录
                    redis_store.rpush(current_app.config.get('RD_TASK_RESULT'), json.dumps(data, cls=JsonToDatetime))
            else:
                # 非实时带宽结果发送到redis 处理队列
                redis_store.rpush(current_app.config.get('RD_TASK_RESULT'), json.dumps(data, cls=JsonToDatetime))
            # 读取对应的system-uuid 下的任务 客户端要执行的任务
            issued_task = redis_store.lpop(current_app.config.get('RD_TASK').format(system_uuid))
            if issued_task:
                # logger.info("task: uuid={}, data:{}".format(system_uuid, issued_task))
                # print({'tasks': json.loads(issued_task)})
                return {'tasks': json.loads(issued_task)}
            else:
                return {'status':200, "msg":"ok"}
        except:
            # logger.error("api post error: {}".format(traceback.format_exc()))
            return {'status': 500, "msg": "Processing failed"}
